package com.listen.service.impl;

import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.listen.common.DateFormatUtil;
import com.listen.common.IPProxyNew;
import com.listen.dao.AddressMapper;
import com.listen.dao.ListenLogMapper;
import com.listen.dao.StartFlagMapper;
import com.listen.dao.StudyMapper;
import com.listen.dao.UserMapper;
import com.listen.model.Address;
import com.listen.model.AddressExample;
import com.listen.model.ListenLog;
import com.listen.model.StartFlag;
import com.listen.model.StartFlagCriteria;
import com.listen.model.Study;
import com.listen.model.StudyCriteria;
import com.listen.model.User;
import com.listen.model.UserCriteria;
import com.listen.model.UserCriteria.Criteria;
import com.listen.service.UserService;
import com.listen.service.DB.AnguanContinueServiceImplDB;
import com.listen.service.DB.AnguanServiceImpl8051;
import com.listen.service.DB.Badayuan;
import com.listen.service.DB.JianZaoShiBixiuDB;
import com.listen.service.DB.JianZaoShiXuanxiuDB;

@Service
public class UserServiceImpl implements UserService {
	
	private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
	
	@Resource
	private UserMapper userMapper;
	
	@Resource
	private StartFlagMapper startFlagMapper;
	
	@Resource
	private AddressMapper addressMapper;
	
	@Resource
	private ListenLogMapper listenLogMapper;
	
	@Resource
	private StudyMapper studyMapper;
	
	@Override
	public int updateSelective(User record) {
		return userMapper.updateByPrimaryKeySelective(record);
	}
	
	@Override
	public List<User> selectByExample(UserCriteria example) {
		example.setOrderByClause(" company_name,zy asc");
		List<User> userList = userMapper.selectByExample(example);
		List<Address> addressList = addressMapper.selectByExample(new AddressExample());
		for(User u :userList){
			String uzy = u.getZy();
			if(uzy==null || "".equals(uzy.trim()))
				continue;
			for(Address a :addressList){
				String azy = a.getZy();
				if(uzy.equalsIgnoreCase(azy)){
					u.setAddress(a.getUrl());
				}
			}
		}
		return userList;
	}
	
	//保存cookie记录
	public int listenEight(User user,int i) throws InterruptedException, UnknownHostException {
		Map<String,Object> resultMap = null;
		int k = 1;
		int result = 0;
		IPProxyNew proxy = new IPProxyNew(this.getProxyURL());
		String ip = proxy.getOneIpAndPort();
		do{
			if(user.getType() == 1) {
				Badayuan badayuan = new Badayuan();
				//记听课cookie信息
				Map<String,Object> msgMap = badayuan.listen(user,ip);
				resultMap = resultMap == null ? new HashMap<String,Object>() :resultMap;
				String msg = (String) (msgMap.get("msg")==null?"":msgMap.get("msg"));
				String successFlag = (String) (msgMap.get("successFlag")==null?"":msgMap.get("successFlag"));
				Study study = (Study) msgMap.get("study");
				if("1".equals(successFlag)) {
					if(study != null) {
						//1.删除同账号同专业的历史cookie记录
						StudyCriteria example = new StudyCriteria();
						example.createCriteria().andCodeEqualTo(user.getCode()).andZyNameEqualTo(user.getZyName());
						studyMapper.deleteByExample(example);
						//插入新的cookie记录
						studyMapper.insertSelective(study);
					}else {
						String dayNum = (String) (msgMap.get("dayNum")==null?"9":msgMap.get("dayNum"));
						user.setTodayNum(Integer.parseInt(dayNum));
						user.setUpdateTm(new Date());
						userMapper.updateByPrimaryKeySelective(user);
					}
					result = 1;
				}
				log.info((i+1)+"-第"+k+"次-"+ip+"-->"+msg);
			}else {
				if(DateFormatUtil.getHour(new Date()) > 0) {
					log.info("第"+(i+1)+"个-"+user.getZyName()+"-"+user.getCode()+"-第"+k+"次,ip:"+ip);
					resultMap = getResultMap(user,ip);
					result = saveInfo(resultMap,user);
				}else {
					result = 1;
					log.info("请在每天1点以后开始听课，当前时间为:"+new Date());
				}
			}
			k++;
			if(result != 1) {
				if(k <=2) {
					ip = proxy.getOneIpAndPort();
				}if(k > 2) {
					//尝试3次不行，则用本机IP
					ip = null;
				}if(k > 3) {
					//尝试5次不行，则放弃
					break;
				}
			}
			Thread.sleep(2000);
		}while(result != 1);
		return result;
	}
	
	private int saveInfo(Map<String,Object> resultMap,User user) {
		String msg = (String) (resultMap.get("msg")==null?"":resultMap.get("msg"));
		String errorMsg = (String) (resultMap.get("errorMsg")==null ? "":resultMap.get("errorMsg"));
		
		//2保存听课日志
		ListenLog log = new ListenLog();
		log.setMsg(msg);
		log.setErrorMsg(errorMsg);
		log.setUid(user.getId());
		log.setCode(user.getCode());
		log.setUpdateTm(new Date());
		log.setClassNo(user.getNowNum());
		listenLogMapper.insertSelective(log);
		
		//3更新听课记录
		String successFlag = (String) resultMap.get("successFlag");
		String dayNum = (String) resultMap.get("dayNum");
		String addNum = (String) resultMap.get("addNum");
		if("1".equals(successFlag)){
			int todayNum = user.getTodayNum();//当天听课节数
			int nowNum = user.getNowNum();//当前总听课节数
			todayNum = todayNum + Integer.parseInt(dayNum);
			nowNum = nowNum+Integer.parseInt(addNum);
			//更新课程状态
			user.setNowNum(nowNum);
			user.setTodayNum(todayNum);
			user.setUpdateTm(new Date());
			updateSelective(user);
			return 1;
		}else
			return 0;
	}
	
	//根据不同的专业调用不同的听课类，获取结果集
	private Map<String,Object> getResultMap(User user,String ipAndPort){
		Map<String,Object> resultMap = null;
		int type = user.getType();
		String zy = user.getZy();
		if(type==2){
			if(zy.equalsIgnoreCase("A") || zy.equalsIgnoreCase("B") || zy.equalsIgnoreCase("C")){
				//三类初培
				AnguanServiceImpl8051 anguan = new AnguanServiceImpl8051();
				resultMap = anguan.lisetn(user,ipAndPort);
			}else if(zy.equalsIgnoreCase("B1")){
				//三类延期
				AnguanContinueServiceImplDB yanqi = new AnguanContinueServiceImplDB();
				resultMap = yanqi.listen(user,ipAndPort);
			}else if(zy.equalsIgnoreCase("A2")){
				//新三类初培
				//AnguanServiceImplNew anguanANew = new AnguanServiceImplNew();
				//resultMap = anguanANew.lisetn(user, ipAndPort);
			}else if(zy.equalsIgnoreCase("B2")){
				//新三类延期
				AnguanContinueServiceImplDB anguanBNew = new AnguanContinueServiceImplDB();
				resultMap = anguanBNew.listen(user, ipAndPort);
			}else {
				System.out.println("---------------专业错误-----------");
			}
		}else if(type==3){
			if(zy.startsWith("JX")){
				//建造师选修
				JianZaoShiXuanxiuDB xuanxiu = new JianZaoShiXuanxiuDB();
				resultMap = xuanxiu.startListen(user,ipAndPort);
			}else if(zy.startsWith("JB")){
				//建造师必修
				JianZaoShiBixiuDB bixiu = new JianZaoShiBixiuDB();
				resultMap = bixiu.startListen(user,ipAndPort);
			}
		}else{
			System.out.println("-----------------听课类型错误--------------");
		}
		return resultMap;
	}

	@Override
	public int insert(Study record) {
		return studyMapper.insert(record);
	}

	@Override
	public Study selectStudy(User user) {
		StudyCriteria example = new StudyCriteria();
		example.createCriteria().andSuccessFlagEqualTo(0).andCodeEqualTo(user.getCode()).andZyNameEqualTo(user.getZyName());
		List<Study> study = studyMapper.selectByExample(example);
		if(study != null && study.size() > 0) {
			return  study.get(0);
		}else {
			return null;
		}
		
	}

	@Override
	public int setTodayNum(User user) {
		return userMapper.updateByPrimaryKeySelective(user);
	}
	

	@Override
	public int updateStartFlag(StartFlag startFlag) {
		return startFlagMapper.updateByPrimaryKey(startFlag);
	}


	@Override
	public StartFlag selectStartFlag(StartFlagCriteria startFlagCriteria) {
		List<StartFlag> startFlag = startFlagMapper.selectByExample(startFlagCriteria);
		if(startFlag !=null && startFlag.size() == 1) {
			return startFlag.get(0);
		}
		return null;
	}

	public List<User> selectByUser(User user) {
		UserCriteria userCriteria = new UserCriteria();
		Criteria criteria = userCriteria.createCriteria();
		criteria.andStatusLessThan(3);
		if(!StringUtils.isBlank(user.getZy())) {
			criteria.andZyEqualTo(user.getZy());
		}
		return userMapper.selectByExample(userCriteria);
	}

	@Override
	public String getProxyURL() {
		AddressExample addressExample = new AddressExample();
		addressExample.createCriteria().andZyEqualTo("IP");
		List<Address> address =  addressMapper.selectByExample(addressExample);
		return address == null ? null : address.get(0).getUrl();
	}
}
